/**
 * 获取积木报表打印地址
 * @param {Array} list   需要转换的数据
 * @param {String} protectValue   保护间隔
 * @param {String} type  子带类型  up上行、down下行
 * @returns {Array}
 */
export function transformSubBandList(list, protectValue, type) {
  if (!list.length) return []
  const _type = type === 'up' ? 'down' : 'up'
  list = mergeSandList(list, type)
  list = list.map(item => {
    if (!item.exchangeRelationList.length) {
      item.render = [
        {
          type: 'guard',
          width: protectValue / item.bandWidth * 100
        },
        { 
          type: 'empty'
        },
        {
          type: 'guard',
          width: protectValue / item.bandWidth * 100
        }
      ]
    } else {
      if (item.exchangeRelationList.length === 1) {
        item.exchangeRelationList = transformRelationList(item.exchangeRelationList, type, _type)
        const left = item.exchangeRelationList[0].BandProtectEndFrenquency - item.exchangeRelationList[0].BandProtectStartFrenquency
        const content = item.exchangeRelationList[0].requestBandWidth
        const other = item.bandWidth - (left + content)

        if (other < 0 && item.mergeList.length) {
          const bandWidth = item.mergeList.length * item.bandWidth
          console.log('bandWidth', bandWidth);
          // 最后 -0.0001 是为了防止正好整除，无法向下取整，得要多个快的长度少一个的效果
          const t = Math.floor((item.exchangeRelationList[0].BandProtectEndFrenquency + item.exchangeRelationList[0].requestBandWidth - item.exchangeRelationList[0].BandProtectStartFrenquency) / item.bandWidth - 0.0001)
          
          const freeSpace = bandWidth - left - content - ((left + content - (t * item.bandWidth)) > protectValue ? 0 : (protectValue - (left + content - t * item.bandWidth)))
          item.render = [
            {
              type: 'guard',
              width: left / bandWidth * 100
            },
            { 
              type: 'relation',
              width: content / bandWidth * 100,
              ...item.exchangeRelationList[0]
            },
            // 中间保护间隔
            {
              type: 'guard',
              width: (left + content - (t * item.bandWidth)) > protectValue ? 0 : (protectValue - (left + content - t * item.bandWidth)) / bandWidth * 100
            },
            { 
              type: 'empty'
            },
            // {
            //   type: 'guard',
            //   width: (freeSpace === 0 ? 0 : (freeSpace < protectValue ? (protectValue - freeSpace) : protectValue) ) / bandWidth * 100
            // },
          ]
          
          if ((left + content - (t * item.bandWidth)) > protectValue) {
            const lastGuardWidth = (item.bandWidth - (left + content - (t * item.bandWidth))) > protectValue ? protectValue : (item.bandWidth - (left + content - (t * item.bandWidth)))
            item.render.push({ type: 'guard', width: lastGuardWidth / bandWidth * 100 })
          }
          console.log('item.render', item.render);
          
        } else if (other === 0) {
          item.render = [
            {
              type: 'guard',
              width: left / item.bandWidth * 100
            },
            { 
              type: 'relation',
              width: content / item.bandWidth * 100,
              ...item.exchangeRelationList[0]
            }
          ]
        } else if (other >= protectValue) {
          item.render = [
            {
              type: 'guard',
              width: left / item.bandWidth * 100
            },
            { 
              type: 'relation',
              width: content / item.bandWidth * 100,
              ...item.exchangeRelationList[0]
            },
            { 
              type: 'empty',
              width: (other - protectValue) / item.bandWidth * 100
            },
            {
              type: 'guard',
              width: protectValue / item.bandWidth * 100
            }
          ]
        } else {
          item.render = [
            {
              type: 'guard',
              width: left / item.bandWidth * 100
            },
            { 
              type: 'relation',
              width: content / item.bandWidth * 100,
              ...item.exchangeRelationList[0]
            },
            {
              type: 'guard',
              width: (item.bandWidth - left - content) / item.bandWidth * 100
            }
          ]
        }
      } else {
        console.log('多个子带--多个用户');
        item.exchangeRelationList = transformRelationList(item.exchangeRelationList, type, _type)
        console.log('item', item);
        console.log('item.exchangeRelationList', item.exchangeRelationList);
        item.render = []
        
        let sunWith = 0
        item.exchangeRelationList.forEach((relationItem, i) => {
          const left = relationItem.BandProtectEndFrenquency - relationItem.BandProtectStartFrenquency
          const content = relationItem.requestBandWidth
          const bandWidth = item.mergeList.length * item.bandWidth
          sunWith += (left*10000 + content*10000)
          // 开始和结束相同
          if (relationItem.BandProtectStartFrenquency === relationItem.BandProtectEndFrenquency) {
            item.render.push(
              { 
                type: 'relation',
                color: i !== 0,
                width: content / bandWidth * 100,
                ...relationItem
              },

            )
          } else {// 开始和结束不同
            item.render.push(
              { type: 'guard', width: left / bandWidth * 100 },
              { 
                type: 'relation',
                color: i !== 0,
                width: content / bandWidth * 100,
                ...relationItem
              },

            )
          }
          
        })
        const bandWidth = item.exchangeRelationList.length * item.bandWidth
        // if ((bandWidth * 100000 - sunWith * 100000) / 100000 >= protectValue) {
        //   debugger
        //   item.render.push(
        //     { type: 'empty' },
        //     { type: 'guard', width: protectValue / bandWidth * 100 }
        //   )
        // } else {
        //   item.render.push(
        //     { type: 'guard', width: (protectValue - (bandWidth * 100000 - sunWith * 100000) / 100000) / bandWidth * 100 }
        //   )
        // }
      }
    }
    return item
  })
  return list
}


/**
 * 对 upSubBandIds 中需要合并的子带进行 标记 并 合并
 * @param {Array} list 
 * @returns {Array}
 */
function mergeSandList(list, type) {
  const subBandIds = type === 'up' ? 'upSubBandIds' : 'downSubBandIds'
  const mergeList = []
  list.forEach(item => {
    if (item.exchangeRelationList.length) {
      item.exchangeRelationList.forEach(relation => {
        if (relation[subBandIds] && relation[subBandIds] !== '') {
          const ids = relation[subBandIds].split(',')
          ids.length > 1 && mergeList.push({ mergeId: relation[subBandIds].replace(/,/g, ''), ids })
        }
      })
    }
  })
  if (mergeList.length) {
    list = list.map(item => {
      mergeList.forEach(merge => {
        if (merge.ids.indexOf(item.id) !== -1) {
          item.mergeId = merge.mergeId
        }
      })
      return item
    })
    let map = {}, tempList = []
    for(let i = 0; i < list.length; i++){
      let item = list[i]
      if (!item.mergeId) {
        tempList.push(item)
      } else {
        if (!map[item.mergeId]) {
          tempList.push(item)
          map[item.mergeId] = [JSON.parse(JSON.stringify(item))]
        } else {
          for (let j = 0; j < tempList.length; j++) {
            let subBand = tempList[j];
            if (subBand.mergeId == item.mergeId) {
              map[item.mergeId].push(item)
              break;
            }
          }
        }
      }
    }
    list = tempList.map(item => {
      if (map[item.mergeId]) {
        item.mergeList = map[item.mergeId]
      }
      return item
    })
    
    list = list.map(item => {
      if (item.mergeList) {
        const arr = []
        item.mergeList.forEach(mergeitem => {
          mergeitem.exchangeRelationList.length && arr.push(...mergeitem.exchangeRelationList)
        })
        item.exchangeRelationList = arr
      }
      return item
    })

    console.log('list', list);
    return list  
  }
  return list
}

/**
 * 对transformSubBandList函数中的 item.exchangeRelationList 进行处理
 * @param {Array} list  
 * @param {String} type 
 * @param {String} _type 
 * @returns {Array}
 */
function transformRelationList(list, type, _type) {
  list.forEach(relation => {
    for (const key in relation) {
      if (key.indexOf(_type) !== -1) {
        // delete relation[key]
      } else if (key.indexOf(type) !== -1 && key !== 'updateBy' && key !== 'updateTime' ) {
        relation[key.replace(type, '')] = relation[key]
        delete relation[key]
      }
    }
  })
  return list
}


/**
 * 判断合理区间
 * @param {Array} data  数据轴: [ [1, 6], [10, 50], [200, 250] ]
 * @param {Array} target  目标区间:[50, 120]
 * @returns {Bolean}
 */
export function judgeReasonable(data, target) {
  // 判断数据的合理性
  if (!(Array.isArray(target) && Array.isArray(data))) return
  if (!target.length) return
  if (target[0] > target[target.legnth - 1]) return
  // 判断是否超过边界值
  if (target[0] < Math.min(...data[0]) || target[1] > Math.max(...data[data.length - 1])) {
    console.log('超过边界值-------------')
    return true
  }
  // 判断是否重叠
  for (let i = 0; i < data.length; i++) {
    const element = data[i]
    if (Math.max(...element) > Math.min(...target) && Math.min(...element) < Math.max(...target)) {
      console.log('重叠了-------------')
      return true
    } else {
      console.log('未重叠--------------')
    }
  }
  return false
}

/**
 * 根据目标id，和长度length，查找的目标id后的数据长度的id集合
 * @param {Array} list 查找的数组
 * @param {String} targetId  查找的目标id
 * @param {String} length  查找的目标id后的数据长度
 * @returns {Array} 查找的目标id后的数据长度的id集合
 */
export function getSubBandIds(list, targetId, length) {
  const ids = []
  let flag = false
  for (let i = 0; i < list.length; i++) {
    const e = list[i]
    if (ids.length >= length) {
      break
    }
    if (e.id === targetId || flag) {
      flag = true
      ids.push(e.id)
    }
  }
  return ids
}


/**
 * 获取积木报表打印地址
 * @param url
 * @param id
 * @param open 是否自动打开
 * @returns {*}
 */
export function demo(list) {
  return list
}
